package com.ming.learn.from.carl.binary.tree;

import com.ming.commons.utils.TreeNode;
import com.sun.jmx.remote.internal.ArrayQueue;

import java.util.ArrayList;
import java.util.List;

public class Of20210305LeetCode637 {
    /*
    给定一个非空二叉树, 返回一个由每层节点平均值组成的数组。
     */
    public static void main(String[] args) {
        System.out.println(averageOfLevels(new TreeNode(1, new TreeNode(2, new TreeNode(4)
                , new TreeNode(5)), new TreeNode(3, new TreeNode(6), new TreeNode(7)))));
    }


    /*
    本题就是层序遍历的时候把一层求个总和再取一个均值。
     */
    private static List<Double> averageOfLevels(TreeNode root){
        ArrayQueue<TreeNode> que = new ArrayQueue<>(10);
        ArrayList<Double> result = new ArrayList<>();
        if (root!=null) que.add(root);
        while (!que.isEmpty()){
            int size = que.size();
            double num=0;
            for (int i = 0; i < size; i++) {
                TreeNode node = que.remove(0);
                num+=node.val;
                if (node.left != null) que.add(node.left);
                if (node.right != null) que.add(node.right);
            }
            result.add(num/+size);
        }
        return result;
    }
}
